﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Data;
using Eassets.Layered.Domain.Asset;
using Eassets.Service.Global;
using Eassets.Layered.Domain.Global;
using Eassets.Service.Asset;

namespace Eassets.UI.Asset
{
    public partial class AssetsTransferOutForm : System.Web.UI.Page
    {
        private DataTable tb;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetIssuingOrganizationLevel();
                GetRequestingOrganizationLevel();
                DataBindToGridViewTransactionDetails();
                //DataBindToGridViewAssetDetails();
                //DataBindToGridViewTransferringAssetDetails();
                GetMainCategory();
                GetSubCategory();
                GetAsset();
                TabContainer2.ActiveTabIndex = 0;



                //DataBindToTransactionDetails();
                //DataBindToItemDetails();
                //DataBindToFixedAssets();
            }
            //DataBindToFixedAssets();
        }

    
        private void GetIssuingOrganizationLevel()
        {
            OrganizationLevelListService organizationLevelListService = new OrganizationLevelListService();
            List<OrganizationLevelList> organizationLevelLists = new List<OrganizationLevelList>();
            organizationLevelLists =
                organizationLevelListService.GetAllOrganizationLevelList().Where(
                    x => x.OrganizationLevelMode == "B" && x.Code == "GAM").ToList();

            dropDownListIssuingOrganizationLevel.DataSource = organizationLevelLists;
            dropDownListIssuingOrganizationLevel.DataValueField = "OrganizationLevelListId";
            dropDownListIssuingOrganizationLevel.DataTextField = "Code";
            dropDownListIssuingOrganizationLevel.DataBind();
        }

        private void GetRequestingOrganizationLevel()
        {
            OrganizationLevelListService organizationLevelListService = new OrganizationLevelListService();
            List<OrganizationLevelList> organizationLevelLists = new List<OrganizationLevelList>();
            organizationLevelLists =
                organizationLevelListService.GetAllOrganizationLevelList().Where(x => x.OrganizationLevelMode == "B").
                    ToList();
            dropDownListRequestingOrganizationLevel.DataSource = organizationLevelLists;
            dropDownListRequestingOrganizationLevel.DataValueField = "OrganizationLevelListId";
            dropDownListRequestingOrganizationLevel.DataTextField = "Code";
            dropDownListRequestingOrganizationLevel.DataBind();
        }

        private void DataBindToGridViewTransactionDetails()
        {
            if (dropDownListRequestingOrganizationLevel.SelectedValue == "0")
            {
                List<Transaction> transactions = null;
                gridViewTransactionDetails.DataSource = transactions;
                gridViewTransactionDetails.DataBind();
            }
            else
            {
                TransactionService transactionService = new TransactionService();
                List<Transaction> transactionList = new List<Transaction>();
                try
                {
                    transactionList =
                        transactionService.GetAllTransaction().Where(
                            x =>
                            x.TransactionDocumentCode == "ARN" &&
                            x.OrganizationLevelListId == Convert.ToInt64(dropDownListRequestingOrganizationLevel.SelectedItem.Value) && x.TransactionStatus == "T").ToList(); 
                            
                    
                    gridViewTransactionDetails.DataSource = transactionList;
                    gridViewTransactionDetails.DataBind();
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }

        protected void gridViewTransactionDetails_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow row = gridViewTransactionDetails.SelectedRow;
            if (row != null)
            {
                //AssetTransferOutDetailsService assetTransferOutDetailsService = new AssetTransferOutDetailsService();

                TransactionService transactionService = new TransactionService();
                long transactionId =
                    transactionService.GetTransactionIdByTransactionNo(
                        gridViewTransactionDetails.SelectedRow.Cells[1].Text);

                DataBindToGridViewAssetDetails(transactionId);

            }
            else
            {
                FlashMessage1.Message = "Please select a row on grid";
                FlashMessage1.CssClass = "errormessage";
                FlashMessage1.Display();
            }
        }

        private void DataBindToGridViewAssetDetails(long transactionId)
        {
            //    List<Assets> assets = null;
            //    gridViewAssetDetails.DataSource = assets;
            //    gridViewAssetDetails.DataBind();

            AssetRequisitionDetailService assetRequisitionDetailService = new AssetRequisitionDetailService();
            List<AssetRequisitionDetail> assetRequisitionDetailList = new List<AssetRequisitionDetail>();

            try
            {
                assetRequisitionDetailList =
                               assetRequisitionDetailService.GetAllAssetRequisitionDetail().Where(
                                   x => x.TransactionId == transactionId).ToList();

                gridViewAssetDetails.DataSource = assetRequisitionDetailList;
                gridViewAssetDetails.DataBind();
            }
            catch (Exception)
            {

                throw;
            }

        }

        private void DataBindToGridViewTransferringAssetDetails()
        {
            //List<Assets> assets = null;
            //gridViewTransferringAssetDetails.DataSource = assets;
            //gridViewTransferringAssetDetails.DataBind();

            try
            {
                foreach (GridViewRow gridViewRow in gridViewAssetDetails.Rows)
                {
                    CheckBox check = ((CheckBox)gridViewRow.Cells[0].FindControl("checkBoxAssets"));

                    if (check.Checked)
                    {
                        DataRow dr = tb.NewRow();
                        dr["AssetId"] = gridViewRow.Cells[1].Text;
                        dr["AssetCode"] = ((Label)gridViewRow.Cells[2].FindControl("labelAssetCode")).Text;
                        dr["RequestedQty"] = gridViewRow.Cells[4].Text;
                        dr["IssuingQty"] = ((TextBox)gridViewRow.Cells[5].FindControl("textBoxIssuingQty")).Text;

                        GridToDT(gridViewAssetDetails);

                        tb.Rows.Add(dr);
                        gridViewTransferringAssetDetails.DataSource = tb;
                        gridViewTransferringAssetDetails.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void GetMainCategory()
        {
            CategoryService categoryService = new CategoryService();
            try
            {
                dropDownListMainCategory.DataSource =
                    categoryService.GetAllAssetCategory().Where(x => x.ParentId == 0).ToList();

                dropDownListMainCategory.DataValueField = "CategoryId";
                dropDownListMainCategory.DataTextField = "Description";
                dropDownListMainCategory.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }


        }

        private void GetSubCategory()
        {
            CategoryService categoryService = new CategoryService();
            List<Category> category = new List<Category>();
            category = null;

            try
            {
                if (dropDownListMainCategory.SelectedValue != "0")
                {
                    category =
                        categoryService.GetAllAssetCategory().Where(
                            x => x.ParentId == Convert.ToInt64(dropDownListMainCategory.SelectedItem.Value)).ToList();

                    dropDownListSubCategory.DataSource = category;
                    dropDownListSubCategory.DataValueField = "CategoryId";
                    dropDownListSubCategory.DataTextField = "Description";
                    dropDownListSubCategory.DataBind();
                }
                else
                {
                    hiddenFieldSubCategory.Value = "0";
                }
            }
            catch (Exception ex)
            {

                throw;
            }

        }

        private void GetAsset()
        {
            AssetService assetService = new AssetService();
            List<Assets> assets = new List<Assets>();
            assets = null;

            try
            {
                if (dropDownListSubCategory.SelectedValue != "0")
                {
                    assets =
                        assetService.GetAllAsset().Where(
                            x => x.AssetCategoryId == Convert.ToInt64(dropDownListSubCategory.SelectedItem.Value)).
                            ToList();

                    dropDownListAsset.DataSource = assets;
                    dropDownListAsset.DataValueField = "AssetId";
                    dropDownListAsset.DataTextField = "Code";
                    dropDownListAsset.DataBind();
                }
                else
                {
                    hiddenFieldAsset.Value = "0";
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        protected void dropDownListIssuingOrganizationLevel_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void dropDownListRequestingOrganizationLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataBindToGridViewTransactionDetails();

        }

        protected void dropDownListRelatedDocuments_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListRelatedDocuments.SelectedIndex == 0)
            {
                TabContainer2.ActiveTabIndex = 0;
            }
            else
            {
                TabContainer2.ActiveTabIndex = 1;
            }

        }

        protected void dropDownListMainCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            dropDownListSubCategory.Dispose();
            dropDownListSubCategory.DataSource = null;
            dropDownListSubCategory.DataBind();

            if (dropDownListMainCategory.SelectedValue == "0")
            {
                hiddenFieldMainCategory.Value = "";
                hiddenFieldSubCategory.Value = "";

                //EmptyDataBindToDropDownList(dropDownListSubCategory);
                dropDownListSubCategory.SelectedValue = "0";
                dropDownListAsset.SelectedValue = "0";
            }
            else
            {
                //hiddenFieldMainCategory.Value = dropDownListMainCategory.SelectedValue;
                GetSubCategory();
            }
        }

        protected void dropDownListSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            dropDownListAsset.Dispose();
            dropDownListAsset.DataSource = null;
            dropDownListAsset.DataBind();

            if (dropDownListSubCategory.SelectedValue == "0")
            {
                hiddenFieldSubCategory.Value = "";
                hiddenFieldAsset.Value = "";
                //EmptyDataBindToDropDownList(dropDownListAsset);
                dropDownListAsset.SelectedValue = "0";
            }
            else
            {
                //hiddenFieldSubCategory.Value = dropDownListSubCategory.SelectedItem.Value;
                GetAsset();
            }
        }

        protected void dropDownListAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListAsset.SelectedValue == "0")
            {
                hiddenFieldAsset.Value = "";
            }
            else
            {
                hiddenFieldAsset.Value = dropDownListAsset.SelectedItem.Value;
            }
        }

        //protected void TabContainer2_OnActiveTabChanged()
        //{
        //    if(TabContainer2.TabIndex == 0)
        //    {
        //        dropDownListRelatedDocuments.SelectedValue = "1";
        //    }
        //    else if(TabContainer2.TabIndex == 1)
        //    {
        //        dropDownListRelatedDocuments.SelectedValue = "2";
        //    }
        //}

        protected void gridViewTransactionDetails_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridViewTransactionDetails.PageIndex = e.NewPageIndex;
            gridViewTransactionDetails.DataBind();
        }

        protected void checkBoxHeaderAssetAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (GridViewRow gridViewRow in ((GridView)((CheckBox)sender).Parent.Parent.Parent.Parent).Rows)
            {
                ((CheckBox)gridViewRow.Cells[0].FindControl("checkBoxAssets")).Checked = ((CheckBox)sender).Checked;
            }
        }

        //protected void gridViewAssetDetails_SelectedIndexChanging(object sender, EventArgs e)
        //{
        //protected void checkBoxAssets_CheckedChanged(object sender, EventArgs e)
        //{
        //    Boolean checkSelect = false;
        //    foreach (GridViewRow gridViewRow in gridViewAssetDetails.Rows)
        //    {
        //        CheckBox check = ((CheckBox)gridViewRow.Cells[0].FindControl("checkBoxAssets"));

        //        if (check.Checked)
        //        {
        //            textBoxAssetCode.Text = ((Label)gridViewRow.Cells[2].FindControl("labelAssetCode")).Text;
        //            textBoxRequestedQuantity.Text = gridViewRow.Cells[4].Text;
        //            textBoxQuantity.Text = gridViewRow.Cells[4].Text;
        //            textBoxAvailableQty.Text = gridViewRow.Cells[4].Text;

        //            checkSelect = true;
        //        }
        //        else
        //        {

        //        }
        //    }
        //    if (checkSelect == false)
        //    {
        //        FlashMessage1.Message = "Select Asset to Apply";
        //        FlashMessage1.CssClass = "errormessage";
        //        FlashMessage1.Display();
        //    }

        //}

        protected void buttonApply_Click(object sender, EventArgs e)
        {
            Boolean checkselect = false;
            try
            {

                foreach (GridViewRow gridViewRow in gridViewAssetDetails.Rows)
                {
                    CheckBox check = ((CheckBox)gridViewRow.Cells[0].FindControl("checkBoxAssets"));

                    if (check.Checked)
                    {
                        if (((TextBox)gridViewRow.Cells[5].FindControl("textBoxIssuingQty")).Text != string.Empty)
                        {
                            //tb = CreateTransferringDetailsDataTable();
                            DataBindToGridViewTransferringAssetDetails();

                            checkselect = true;
                        }
                        else
                        {
                            FlashMessage1.Message = "Please mention the Issuing Quantity";
                            FlashMessage1.CssClass = "errormessage";
                            FlashMessage1.Display();
                        }

                    }
                    else
                    {
                        FlashMessage1.Message = "Please select a Row on Grid";
                        FlashMessage1.CssClass = "errormessage";
                        FlashMessage1.Display();
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }

            //if (checkselect == false)
            //{
            //    FlashMessage1.Message = "Applying Failed";
            //    FlashMessage1.CssClass = "errormessage";
            //    FlashMessage1.Display();
            //}
        }

        private DataTable CreateTransferringDetailsDataTable()
        {
            DataTable dt = new DataTable("Details");

            dt.Columns.Add("AssetId");
            dt.Columns.Add("AssetCode");
            dt.Columns.Add("RequestedQty");
            dt.Columns.Add("IssuingQty");

            return dt;
        }

        private void GridToDT(GridView gv)
        {
            DataTable dt = new DataTable("Details");

            dt.Columns.Add("AssetId");
            dt.Columns.Add("AssetCode");
            dt.Columns.Add("RequestedQty");
            dt.Columns.Add("IssuingQty");

            foreach (GridViewRow row in gv.Rows)
            {
                DataRow dtrow = tb.NewRow();

                dtrow[0] = row.Cells[1].Text;
                dtrow[1] = row.Cells[2].Text;
                dtrow[2] = row.Cells[4].Text;
                dtrow[3] = row.Cells[5].Text;

                tb.Rows.Add(dtrow);
            }
        }

        protected void textBoxQuantity_TextChanged(object sender, EventArgs e)
        {
            Boolean checkselect = false;
            foreach (GridViewRow gridViewRow in gridViewAssetDetails.Rows)
            {
                CheckBox check = ((CheckBox)gridViewRow.Cells[0].FindControl("checkBoxAssets"));

                if (check.Checked)
                {
                    int ReqQty = Convert.ToInt16(gridViewRow.Cells[4].Text);
                    int IssQty = Convert.ToInt16(((TextBox)gridViewRow.Cells[5].FindControl("textBoxIssuingQty")).Text);
                    int AvaQty = Convert.ToInt16(((Label)gridViewRow.Cells[6].FindControl("labelAvailableQty")).Text);

                    if (IssQty == ReqQty && IssQty <= AvaQty)
                    {

                    }
                    else
                    {
                        ((TextBox)gridViewRow.Cells[5].FindControl("textBoxIssuingQty")).Text = string.Empty;

                        FlashMessage1.Message = "Issuing Qty can not be accepted";
                        FlashMessage1.CssClass = "errormessage";
                        FlashMessage1.Display();
                    }

                    checkselect = true;
                }
            }

            if (checkselect == false)
            {
                FlashMessage1.Message = "Please select a Row on Grid";
                FlashMessage1.CssClass = "errormessage";
                FlashMessage1.Display();
            }
        }

        protected void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                AddDataToTransaction();
                AddDataToOrganizationLevelListAsset();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private void AddDataToTransaction()
        {
            TransactionService transactionService = new TransactionService();
            Transaction transaction = new Transaction();

            transaction.TransactionTypeCode = Convert.ToString("FATRO");
            transaction.TransactionDocumentCode = Convert.ToString("TRO");
            transaction.CompanyId = 0;
            transaction.OrganizationLevelListId = Convert.ToInt64(dropDownListIssuingOrganizationLevel.SelectedItem.Value);

            int serial = Getserial();
            string transactionNo = Convert.ToString(CreateNewTransactionCode((serial + 1)));
            transaction.TransactionNo = transactionNo;
            transaction.TransactionUserId = 0; //Convert.ToInt64(dropDownListRequestingPerson.SelectedValue);
            transaction.TransactionStatus = "O";
            transaction.TransactionDate = DateTime.Now;

            transactionService.AddTransaction(transaction);
            
        }

        private void AddDataToOrganizationLevelListAsset()
        {
            int noOfRows = gridViewTransferringAssetDetails.Rows.Count;
                for (int i = 0; i < noOfRows; i++)
                {
                    AssetTransferOutDetailsService assetTransferOutDetailsService = new AssetTransferOutDetailsService();

                    OrganizationLevelListAssetService organizationLevelListAssetService = new OrganizationLevelListAssetService();
                    OrganizationLevelListAsset organizationLevelListAsset = new OrganizationLevelListAsset();

                    organizationLevelListAsset.OrganizationLevelListAssetId =
                        Convert.ToInt64(dropDownListIssuingOrganizationLevel.SelectedItem.Value);
                    organizationLevelListAsset.AssetId =
                        Convert.ToInt64(gridViewTransferringAssetDetails.SelectedRow.Cells[1].Text);

                    long availableQty =
                        assetTransferOutDetailsService.GetNoOfAssetsInOrganizationLevelListAssetByAssetId(
                            organizationLevelListAsset.AssetId);
                    long issuingQty = Convert.ToInt64(gridViewTransferringAssetDetails.SelectedRow.Cells[3].Text);

                    organizationLevelListAsset.NoOfAssets = (availableQty - issuingQty);

                    organizationLevelListAssetService.AddOrganizationLevelListAsset(organizationLevelListAsset);
                }
            
        }

        private int Getserial()
        {
            long transactionSerial = 0;
            TransactionSerialService transactionSerialService = new TransactionSerialService();

            transactionSerial = transactionSerialService.GetMaxTransactionSerialByWorkFlowDocumentCode("TRO");
            return Convert.ToInt16(transactionSerial);
        }

        private String CreateNewTransactionCode(int maxSerial)
        {
            string maxSerialFormated;
            maxSerialFormated = CreateNumberFormat(Convert.ToInt16(maxSerial));
            Regex regex = new Regex("-");
            string locationCode = dropDownListIssuingOrganizationLevel.SelectedItem.Text;
            string[] arrayParameters = regex.Split(locationCode);
            String yearMonth = DateTime.Now.ToString("yyyyMM");

            string OrganizationLevelListCode = Convert.ToString(arrayParameters[0]);

            string NewTransactionCode = (OrganizationLevelListCode + "/"
                                     + "TRO" + "/"
                                     + yearMonth + "/"
                                   + maxSerialFormated);
            return NewTransactionCode;
        }

        private String CreateNumberFormat(Int16 maxSerial)
        {
            string maxSerialCode;
            if ((maxSerial / 10) == 0)
            {
                maxSerialCode = "0000" + maxSerial;
            }
            else if ((maxSerial / 100) == 0)
            {
                maxSerialCode = "000" + maxSerial;
            }
            else if ((maxSerial / 1000) == 0)
            {
                maxSerialCode = "00" + maxSerial;
            }
            else if ((maxSerial / 10000) == 0)
            {
                maxSerialCode = "0" + maxSerial;
            }
            else
            {
                maxSerialCode = maxSerial.ToString();
            }
            return maxSerialCode;
        }
    }
}
